/**
  ******************************************************************************
  * @file    iap.c 
  * @author  iron
  * @date 	 2018-07-09
  * @version v1.0
  * @brief   iap c file
  */

/** @addtogroup IAP_GROUP
  * @{
  */ 

/* includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include "iap.h"

/* variables ----------------------------------------------------------------*/
uint8_t iap_filename[IAP_FILE_NAME_LENGTH + 1];

/* private typedef -----------------------------------------------------------*/
typedef  void (*pFunction)(void);

/* private define ------------------------------------------------------------*/
#define IS_CAP_LETTER(c)    (((c) >= 'A') && ((c) <= 'F'))
#define IS_LC_LETTER(c)     (((c) >= 'a') && ((c) <= 'f'))
#define IS_09(c)            (((c) >= '0') && ((c) <= '9'))
#define ISVALIDHEX(c)       (IS_CAP_LETTER(c) || IS_LC_LETTER(c) || IS_09(c))
#define ISVALIDDEC(c)       IS_09(c)
#define CONVERTDEC(c)       (c - '0')

#define CONVERTHEX_ALPHA(c) (IS_CAP_LETTER(c) ? ((c) - 'A'+10) : ((c) - 'a'+10))
#define CONVERTHEX(c)       (IS_09(c) ? ((c) - '0') : CONVERTHEX_ALPHA(c))

/* private macro -------------------------------------------------------------*/
/* private variables ---------------------------------------------------------*/
/* private function prototypes -----------------------------------------------*/
/* private functions ---------------------------------------------------------*/


/**
  * @brief  function_0 description
  * @param  p_data
  * @param  p_length
  *     0: length = 0; 
  *     2: length = 2; 
  *    >0: length > 0; 
  * @param  timeout
  * @retval OK: normally return;
  *         ERROR: error;
  */
void iap_delay(uint32_t time_ms)
{
	HAL_Delay(time_ms);
}

/**
  * @brief  Convert an Integer to a string
  * @param  p_str: The string output pointer
  * @param  intnum: The integer to be converted
  * @retval None
  */
void iap_int2str(uint8_t *p_str, uint32_t intnum)
{
  uint32_t i, divider = 1000000000, pos = 0, status = 0;

  for (i = 0; i < 10; i++)
  {
    p_str[pos++] = (intnum / divider) + 48;

    intnum = intnum % divider;
    divider /= 10;
    if ((p_str[pos-1] == '0') & (status == 0))
    {
      pos = 0;
    }
    else
    {
      status++;
    }
  }
}


/**
  * @brief  Convert a string to an integer
  * @param  p_inputstr: The string to be converted
  * @param  p_intnum: The integer value
  * @retval 1: Correct
  *         0: Error
  */
uint32_t iap_str2int(uint8_t *p_inputstr, uint32_t *p_intnum)
{
  uint32_t i = 0, res = 0;
  uint32_t val = 0;

  if ((p_inputstr[0] == '0') && ((p_inputstr[1] == 'x') || (p_inputstr[1] == 'X')))
  {
    i = 2;
    while ( ( i < 11 ) && ( p_inputstr[i] != '\0' ) )
    {
      if (ISVALIDHEX(p_inputstr[i]))
      {
        val = (val << 4) + CONVERTHEX(p_inputstr[i]);
      }
      else
      {
        /* Return 0, Invalid input */
        res = 0;
        break;
      }
      i++;
    }

    /* valid result */
    if (p_inputstr[i] == '\0')
    {
      *p_intnum = val;
      res = 1;
    }
  }
  else /* max 10-digit decimal input */
  {
    while ( ( i < 11 ) && ( res != 1 ) )
    {
      if (p_inputstr[i] == '\0')
      {
        *p_intnum = val;
        /* return 1 */
        res = 1;
      }
      else if (((p_inputstr[i] == 'k') || (p_inputstr[i] == 'K')) && (i > 0))
      {
        val = val << 10;
        *p_intnum = val;
        res = 1;
      }
      else if (((p_inputstr[i] == 'm') || (p_inputstr[i] == 'M')) && (i > 0))
      {
        val = val << 20;
        *p_intnum = val;
        res = 1;
      }
      else if (ISVALIDDEC(p_inputstr[i]))
      {
        val = val * 10 + CONVERTDEC(p_inputstr[i]);
      }
      else
      {
        /* return 0, Invalid input */
        res = 0;
        break;
      }
      i++;
    }
  }

  return res;
}

/**
  * @brief  Download a file via serial port
  * @param  None
  * @retval None
  */
void SerialDownload(void)
{
  uint8_t number[11] = {0};
  uint32_t size = 0;
  int result;

  iap_uart_send_str((uint8_t *)"Waiting for the file to be sent ... (press 'a' to abort)\n\r");
	
  result = iap_ymodem_receive( &size );
	
  if (result == IAP_YMODEM_OK)
  {
    iap_uart_send_str((uint8_t *)"\n\n\r Programming Completed Successfully!\n\r--------------------------------\r\n Name: ");
    iap_uart_send_str(iap_filename);
		
    iap_int2str(number, size);
		
    iap_uart_send_str((uint8_t *)"\n\r Size: ");
    iap_uart_send_str(number);
    iap_uart_send_str((uint8_t *)" Bytes\r\n");
    iap_uart_send_str((uint8_t *)"-------------------\n");
  }
  else if (result == IAP_YMODEM_LIMIT)
  {
    iap_uart_send_str((uint8_t *)"\n\n\rThe image size is higher than the allowed space memory!\n\r");
  }
  else if (result == IAP_YMODEM_DATA)
  {
    iap_uart_send_str((uint8_t *)"\n\n\rVerification failed!\n\r");
  }
  else if (result == IAP_YMODEM_ABORT)
  {
    iap_uart_send_str((uint8_t *)"\r\n\nAborted by user.\n\r");
  }
  else
  {
    iap_uart_send_str((uint8_t *)"\n\rFailed to receive the file!\n\r");
  }
}

/**
  * @brief  Upload a file via serial port.
  * @param  None
  * @retval None
  */
void SerialUpload(void)
{
  uint8_t result = 0;

  iap_uart_send_str((uint8_t *)"\n\n\rSelect Receive File\n\r");

  result = iap_uart_getc(IAP_UART_GETC_TIMEOUT);
	
  if ( result == CRC16)
  {
    /* Transmit the flash image through ymodem protocol */
    result = iap_ymodem_transmit((uint8_t*)APP_FLASH_START_ADDRESS, (const uint8_t*)"UploadedFlashImage.bin", APP_FLASH_SIZE);

    if (result != 0)
    {
      iap_uart_send_str((uint8_t *)"\n\rError Occurred while Transmitting File\n\r");
    }
    else
    {
      iap_uart_send_str((uint8_t *)"\n\rFile uploaded successfully \n\r");
    }
  }
}

/**
  * @brief  Display the Main Menu on HyperTerminal
  * @param  None
  * @retval None
  */
void iap_menu(void)
{
  uint8_t key = 0;
	uint32_t FlashProtection = 0;
	
  iap_uart_send_str((uint8_t *)"\r\n======================================================================");
  iap_uart_send_str((uint8_t *)"\r\n=              (C) COPYRIGHT 2018 Hand-HiTech                        =");
  iap_uart_send_str((uint8_t *)"\r\n=                                                                    =");
  iap_uart_send_str((uint8_t *)"\r\n=                       By Iron                                      =");
  iap_uart_send_str((uint8_t *)"\r\n======================================================================");
  iap_uart_send_str((uint8_t *)"\r\n\r\n");

  while (1)
  {
    /* Test if any sector of Flash memory where user application will be loaded is write protected */
    FlashProtection = iap_flash_get_write_protection_status();
    
    iap_uart_send_str((uint8_t *)"\r\n=================== Main Menu ============================\r\n\n");
    iap_uart_send_str((uint8_t *)"  Download image to the internal Flash ----------------- 1\r\n\n");
    iap_uart_send_str((uint8_t *)"  Upload image from the internal Flash ----------------- 2\r\n\n");
    iap_uart_send_str((uint8_t *)"  Execute the loaded application ----------------------- 3\r\n\n");

    if(FlashProtection != FLASHIF_PROTECTION_NONE)
    {
      iap_uart_send_str((uint8_t *)"  Disable the write protection ------------------------- 4\r\n\n");
    }
    else
    {
      iap_uart_send_str((uint8_t *)"  Enable the write protection -------------------------- 4\r\n\n");
    }
    iap_uart_send_str((uint8_t *)"==========================================================\r\n\n");

    /* Clean the input path */
    iap_uart_rx_flush();
	
    /* Receive key */
    key = iap_uart_getc(IAP_UART_GETC_TIMEOUT);

    switch (key)
    {
    case '1' :
      /* Download user application in the Flash */
      SerialDownload();
		  iap_delay(1000);
      break;
		
    case '2' :
      /* Upload user application from the Flash */
      SerialUpload();
		  iap_delay(1000);
      break;
		
    case '3' :
		{
			pFunction JumpToApplication;
			uint32_t JumpAddress;
			
      iap_uart_send_str((uint8_t *)"Start program execution......\r\n\n");
			
      /* execute the new program */
      JumpAddress = *(__IO uint32_t*) (APP_FLASH_START_ADDRESS + 4);
      /* Jump to user application */
      JumpToApplication = (pFunction) JumpAddress;
      /* Initialize user application's Stack Pointer */
      __set_MSP(*(__IO uint32_t*) APP_FLASH_START_ADDRESS);
      JumpToApplication();
		}
      break;
		
    case '4' :
      if (FlashProtection != FLASHIF_PROTECTION_NONE)
      {
        /* Disable the write protection */
        if (ipa_flash_write_protection_config(OB_WRPSTATE_DISABLE) == HAL_OK)
        {
          iap_uart_send_str((uint8_t *)"Write Protection disabled...\r\n");
          iap_uart_send_str((uint8_t *)"System will now restart...\r\n");
          /* Launch the option byte loading */
          HAL_FLASH_OB_Launch();
          /* Ulock the flash */
          HAL_FLASH_Unlock();
        }
        else
        {
          iap_uart_send_str((uint8_t *)"Error: Flash write un-protection failed...\r\n");
        }
      }
      else
      {
        if (ipa_flash_write_protection_config(OB_WRPSTATE_ENABLE) == HAL_OK)
        {
          iap_uart_send_str((uint8_t *)"Write Protection enabled...\r\n");
          iap_uart_send_str((uint8_t *)"System will now restart...\r\n");
          /* Launch the option byte loading */
          HAL_FLASH_OB_Launch();
        }
        else
        {
          iap_uart_send_str((uint8_t *)"Error: Flash write protection failed...\r\n");
        }
      }
      break;
			
    default:
			/* Abort ymodem communication */
			iap_uart_putc(CA);
			iap_uart_putc(CA);
		
			iap_uart_send_str((uint8_t *)"Invalid Number ! ==> The number should be either 1, 2, 3 or 4\r\n\r\n");
			
			break;
    }
  }
}

/**
  * @brief  iap_main
  */
void iap_main(void)
{
  /* Test if Key push-button is pressed */
  if (1)
  { 
    /* Execute the IAP driver in order to reprogram the Flash */
    iap_uart_init();
		
    /* Display main menu */
    iap_menu ();
  }

	/* Test if user code is programmed starting from address "APPLICATION_ADDRESS" */
	if (((*(__IO uint32_t*)APP_FLASH_START_ADDRESS) & 0x2FFE0000 ) == 0x20000000)
	{
		pFunction JumpToApplication;
		uint32_t JumpAddress;
		
		/* Jump to user application */
		JumpAddress = *(__IO uint32_t*) (APP_FLASH_START_ADDRESS + 4);
		JumpToApplication = (pFunction) JumpAddress;
		
		/* Initialize user application's Stack Pointer */
		__set_MSP(*(__IO uint32_t*) APP_FLASH_START_ADDRESS);
		JumpToApplication();
	}
	
	// on app start error, system reset.
	while(1)
	{
		iap_delay(1000);
		NVIC_SystemReset();
	}
}

/**
  * @}
  */

/*******************(C)COPYRIGHT 2018 Iron *****END OF FILE*******************/
